Padding with spaces to a fixed-length string

By  Dimitre Novatchev
 
Language  XSLT
Category designpatterns, xml, msxml, html
Posted 20  Mar  2001
Updated 20  Mar  2001
 
Summary
This snippet shows how to pad a given string with spaces to a given fixed length. Two non-recursive templates are presented. Demonstrated is how to specify white-space only nodes within a variable's contents.
 
This is a repeated FAQ:
 
"I have a string, which I need to pad with spaces so that the result will occupy exactly 10 characters. Can this be done with XSLT?"
 
The answer is an "yes" as demonstrated by the code below.
 
While a general recursive approach for iterating N times and outputting a space on each iteration, here we present another, non-recursive approach.
 
The idea is that if we know in advance the maximum length to which strings will have to be padded, then we could declare an xsl:variable holding a string of spaces with at least this maximum length.
 
The rest is just some simple calculation of lengths and using the substring function.
 
The code below performs right-padding a string. A very small modification is needed so that left-padding will be performed just change:
substring(concat($String,$spaces),1,$length)
to
concat(substring($spaces, 1, $length - string-length($String)), $String)
 
Another thing to note is the xml:space="preserve" in one of the definitions of the "spaces" variable.
 
Why is this necessary? As we know, the msxml3 parser discards on default all whitespace-only nodes. Without specifying the "preserve" value for the xml:space attribute, it would not be possible to specify the necessary number of spaces as a single text node within the contents of the variable.
 
Another thing to note is that if we intend to present the resulting padded string by a browser, we need to enclose it with <pre> (or <q>, or <blockquote>) tags, or translate all spaces to &#xA; so that the browser will not ignore the spaces.
 
code
 
 
XSL Stylesheet
 
 
XML/HTML Result:
 
 
Text Result: